package com.sch.wanandroid.ui.my.share

import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.view.*
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.coder.zzq.smartshow.dialog.DialogBtnClickListener
import com.coder.zzq.smartshow.dialog.EnsureDialog
import com.coder.zzq.smartshow.dialog.SmartDialog
import com.coder.zzq.smartshow.toast.SmartToast
import com.sch.wanandroid.R
import com.sch.wanandroid.adapter.MyArticleAdapter
import com.sch.wanandroid.base.BaseActivity
import com.sch.wanandroid.constants.Constants
import com.sch.wanandroid.entity.ArticleBean
import com.sch.wanandroid.ui.addshare.AddShareActivity
import com.sch.wanandroid.ui.web.WebActivity
import kotlinx.android.synthetic.main.activity_myshare.*

/**
 * Created by Sch.
 * Date: 2020/4/28
 * description:我的文章
 */
class MyShareActivity : BaseActivity() {
    private lateinit var myShareViewModel: MyShareViewModel

    private val articleAdapter by lazy { MyArticleAdapter() }
    private var pageNum = 1
    private val articleList by lazy { mutableListOf<ArticleBean>() }
    private var delatePosition: Int = 0

    private val delateDialog by lazy {
        EnsureDialog().message("是否删除该文章")
            .cancelBtn("取消")
            .confirmBtn("确定", object : DialogBtnClickListener<SmartDialog<*>> {
                override fun onBtnClick(p0: SmartDialog<*>?, p1: Int, p2: Any?) {
                    p0?.dismiss()
                    myShareViewModel.deleteArticle(articleList[delatePosition].id)
                }
            })
    }

    override fun init(savedInstanceState: Bundle?) {
        initTitle("我的分享")
        myShareViewModel = ViewModelProvider(this).get(MyShareViewModel::class.java)

        initListener()
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = articleAdapter
        recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER//取消滑动到顶部边界越界效果

        myShareViewModel.articleListLiveData.observe(this, Observer {
            setData(it)
        })
        myShareViewModel.errorMsg.observe(this) {
            onError(it)
        }
        myShareViewModel.deleteSuccess.observe(this) {
            if (it) {
                deleteArticleSuccess()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        //加载中动画
        loadingTip.loading()
        loadData()
    }
    private fun loadData() {
        articleList.clear()
        articleAdapter.setList(articleList)
        pageNum = 1
        myShareViewModel.getArticleData(pageNum)
    }

    private fun initListener() {
        articleAdapter.setOnItemClickListener { adapter, view, position ->
            intent(Bundle().apply {
                putString(Constants.WEB_URL, articleList[position].link)
                putString(Constants.WEB_TITLE, articleList[position].title)
            }, WebActivity::class.java, false)
        }
        articleAdapter.setOnItemLongClickListener { adapter, view, position ->
            delatePosition = position
            delateDialog.showInActivity(this@MyShareActivity)
        }
        // 设置无网络时重新加载点击事件
        loadingTip.setReloadListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                loadingTip.loading()
                loadData()
            }
        })
        //下拉监听
        smartRefresh.setOnRefreshListener {
            loadData()
        }
        smartRefresh.setOnLoadMoreListener {
            pageNum++
            myShareViewModel.getArticleData(pageNum)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_myshare
    }

    fun setData(list: List<ArticleBean>) {
        dismissRefresh()
        if (list.isNotEmpty()) {
            articleList.addAll(list)
            articleAdapter.setList(articleList)
        } else {
            if (articleList.size == 0) loadingTip.showEmpty()
            else SmartToast.info("没有更多数据了")
        }
    }

    fun onError(ex: String?) {
        //请求失败将page -1
        if (pageNum > 0) pageNum--
        dismissRefresh()
        if (articleList.size == 0) {
            loadingTip.showInternetError()
        }
        SmartToast.error(ex)
    }

    private fun deleteArticleSuccess() {
        if (delatePosition < articleList.size) {
            articleList.removeAt(delatePosition)
            articleAdapter.removeAt(delatePosition)
            if (articleList.size == 0) loadingTip.showEmpty()
        }
    }

    /**
     * 隐藏刷新加载
     */
    private fun dismissRefresh() {
        loadingTip.dismiss()
        if (smartRefresh.state.isOpening) {
            smartRefresh.finishLoadMore()
            smartRefresh.finishRefresh()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_square, menu)
        return super.onCreateOptionsMenu(menu)
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_add -> {
                intent(AddShareActivity::class.java, true)
            }
        }
        return super.onOptionsItemSelected(item)
    }
}